import Component from '@glimmer/component';
import { action } from '@ember/object';
import { tracked } from '@glimmer/tracking';
import { service } from '@ember/service';

export default class TeamProjectGanttChartComponent extends Component {
  @service api;
  
  @tracked hideWeekends = true;
  @tracked hideHiddenDates = true;
  @tracked queryStartTime = '';
  @tracked queryEndTime = '';
  @tracked isLoading = false;
  @tracked filteredParticipants = [];

  constructor() {
    super(...arguments);
    this.initializeTimeRange();
    // 在构造函数中设置初始数据加载
    this.loadInitialData();
  }

  // 当组件参数变化时重新加载数据
  didReceiveAttrs() {
    super.didReceiveAttrs();
    console.log('甘特图组件接收到参数变化:', {
      participants: this.args.participants?.length || 0,
      members: this.args.members?.length || 0,
      requirements: this.args.requirements?.length || 0
    });
    
    // 直接检查并加载数据
    this.checkAndLoadData();
  }

  // 初始数据加载
  loadInitialData() {
    // 延迟执行，确保组件已完全初始化
    setTimeout(() => {
      this.checkAndLoadData();
    }, 100);
  }

  // 检查并加载数据
  checkAndLoadData() {
    if (this.args.participants && this.args.participants.length > 0 && this.args.members && this.args.members.length > 0) {
      console.log('数据完整，开始加载筛选后的参与人员数据...');
      this.loadFilteredParticipants();
    } else {
      console.log('数据不完整，跳过加载:', {
        hasParticipants: !!this.args.participants,
        participantsLength: this.args.participants?.length || 0,
        hasMembers: !!this.args.members,
        membersLength: this.args.members?.length || 0
      });
    }
  }

  get participants() {
    return this.args.participants || [];
  }

  get hiddenDates() {
    return this.args.hiddenDates || [];
  }

  // 初始化时间范围（当前时间±14天）
  initializeTimeRange() {
    const today = new Date();
    const startDate = new Date(today);
    startDate.setDate(today.getDate() - 14);
    const endDate = new Date(today);
    endDate.setDate(today.getDate() + 7);
    
    this.queryStartTime = startDate.toISOString().split('T')[0];
    this.queryEndTime = endDate.toISOString().split('T')[0];
  }

  // 获取需求数据
  get requirements() {
    const requirements = this.args.requirements || [];
    // 转换为映射格式，便于查找
    const requirementMap = {};
    requirements.forEach(req => {
      requirementMap[req.id] = req;
    });
    return requirementMap;
  }

  // 加载筛选后的参与人员数据（客户端筛选）
  async loadFilteredParticipants() {
    this.isLoading = true;
    
    try {
      // 使用父组件传递的全量数据，在客户端进行筛选
      const allParticipants = this.args.participants || [];
      
      // 应用时间筛选条件 - 放宽条件：只要任务与筛选时间范围有重叠就显示
      let filtered = allParticipants.filter(participant => {
        // 跳过没有开始时间或结束时间的记录
        if (!participant.startTime || !participant.endTime) return false;
        
        const taskStart = new Date(participant.startTime);
        const taskEnd = new Date(participant.endTime);
        
        // 如果没有设置筛选时间，显示所有任务
        if (!this.queryStartTime && !this.queryEndTime) {
          return true;
        }
        
        // 如果只设置了开始时间，显示开始时间之后的任务
        if (this.queryStartTime && !this.queryEndTime) {
          const filterStart = new Date(this.queryStartTime);
          return taskEnd >= filterStart;
        }
        
        // 如果只设置了结束时间，显示结束时间之前的任务
        if (!this.queryStartTime && this.queryEndTime) {
          const filterEnd = new Date(this.queryEndTime);
          return taskStart <= filterEnd;
        }
        
        // 如果设置了完整的时间范围，显示与范围有重叠的任务
        if (this.queryStartTime && this.queryEndTime) {
          const filterStart = new Date(this.queryStartTime);
          const filterEnd = new Date(this.queryEndTime);
          
          // 任务与筛选范围有重叠的条件：
          // 任务开始时间 <= 筛选结束时间 AND 任务结束时间 >= 筛选开始时间
          return taskStart <= filterEnd && taskEnd >= filterStart;
        }
        
        return true;
      });
      
      // 获取所有成员（从父组件传递的数据）
      const members = this.args.members || [];
      
      // 按成员分组并合并相同需求的任务
      const memberGroups = {};
      
      // 先初始化所有成员
      members.forEach(member => {
        memberGroups[member.id] = {
          memberId: member.id,
          memberName: member.name,
          requirements: {}
        };
      });
      
      // 然后添加有任务的成员数据
      filtered.forEach(participant => {
        const memberId = participant.memberId;
        if (!memberGroups[memberId]) {
          memberGroups[memberId] = {
            memberId: memberId,
            memberName: participant.memberName,
            requirements: {}
          };
        }
        
        const requirementId = participant.requirementId;
        if (requirementId) { // 确保requirementId存在
          if (!memberGroups[memberId].requirements[requirementId]) {
            memberGroups[memberId].requirements[requirementId] = [];
          }
          
          memberGroups[memberId].requirements[requirementId].push(participant);
        }
      });
      
      // 创建合并后的参与记录
      const mergedParticipants = [];
      Object.values(memberGroups).forEach(memberGroup => {
        const requirementGroups = Object.values(memberGroup.requirements);
        
        if (requirementGroups.length > 0) {
          // 有任务的成员
          requirementGroups.forEach(requirementGroup => {
            if (requirementGroup.length > 0) {
              const baseParticipant = requirementGroup[0];
              const startTimes = requirementGroup.map(p => new Date(p.startTime)).filter(Boolean);
              const endTimes = requirementGroup.map(p => new Date(p.endTime)).filter(Boolean);
              
              const mergedParticipant = {
                ...baseParticipant,
                memberId: memberGroup.memberId,
                memberName: memberGroup.memberName,
                startTime: startTimes.length > 0 ? new Date(Math.min(...startTimes)).toISOString().split('T')[0] : '',
                endTime: endTimes.length > 0 ? new Date(Math.max(...endTimes)).toISOString().split('T')[0] : '',
                workload: requirementGroup.reduce((sum, p) => sum + (p.workload || 0), 0)
              };
              
              mergedParticipants.push(mergedParticipant);
            }
          });
        } else {
          // 没有任务的成员，创建空记录
          mergedParticipants.push({
            memberId: memberGroup.memberId,
            memberName: memberGroup.memberName,
            requirementId: null,
            requirementName: null,
            startTime: null,
            endTime: null,
            workload: 0,
            role: '',
            workItem: ''
          });
        }
      });
      
      this.filteredParticipants = mergedParticipants;
      
      // 调试信息：显示加载的数据
      console.log('客户端筛选后的参与人员数据:', {
        totalParticipants: allParticipants.length,
        filteredParticipants: mergedParticipants.length,
        data: mergedParticipants
      });
      
      // 强制重新渲染
      this.filteredParticipants = [...this.filteredParticipants];
    } catch (error) {
      console.error('客户端筛选参与人员数据失败:', error);
      this.filteredParticipants = [];
    } finally {
      this.isLoading = false;
    }
  }

  // 获取所有成员
  get uniqueMembers() {
    const members = this.args.members || [];
    return members.map(member => ({
      memberId: member.id,
      memberName: member.name
    }));
  }

  // 按成员分组参与人员
  get groupedParticipants() {
    return this.uniqueMembers.map(member => {
      const memberParticipants = this.filteredParticipants.filter(p => p.memberId === member.memberId);
      return {
        ...member,
        participants: memberParticipants
      };
    });
  }

  // 获取可见的日期范围 - 显示当前时间的上两周和下一周
  get visibleDates() {
    const allDates = this.getAllDates();
    let filteredDates = allDates;

    if (this.hideWeekends) {
      filteredDates = filteredDates.filter(date => !this.isWeekend(date));
    }

    if (this.hideHiddenDates) {
      filteredDates = filteredDates.filter(date => !this.hiddenDates.includes(date));
    }

    return filteredDates;
  }

  // 获取所有日期范围 - 根据时间筛选范围显示
  getAllDates() {
    const dates = new Set();
    
    // 使用筛选的时间范围，如果没有设置则使用默认范围
    const startDate = this.queryStartTime ? new Date(this.queryStartTime) : new Date();
    const endDate = this.queryEndTime ? new Date(this.queryEndTime) : new Date();
    
    // 如果没有设置结束时间，默认显示7天
    if (!this.queryEndTime) {
      endDate.setDate(endDate.getDate() + 7);
    }
    
    // 如果没有设置开始时间，默认显示前14天
    if (!this.queryStartTime) {
      startDate.setDate(startDate.getDate() - 14);
    }
    
    // 生成日期范围
    const current = new Date(startDate);
    while (current <= endDate) {
      dates.add(this.formatDateForKey(current));
      current.setDate(current.getDate() + 1);
    }

    return Array.from(dates).sort();
  }

  // 获取某天某成员正在处理的所有需求（支持并行开发，预占位确保位置一致）
  @action
  getRequirementsForDate(memberId, date) {
    const memberParticipants = this.filteredParticipants.filter(p => p.memberId === memberId);
    const allMemberRequirements = [];
    
    // 收集该成员参与的所有需求
    memberParticipants.forEach(participant => {
      // 跳过没有需求ID的记录（无任务人员的空记录）
      if (!participant.requirementId) return;
      
      if (!participant.startTime || !participant.endTime) return;
      
      const requirement = this.requirements[participant.requirementId];
      if (requirement && !allMemberRequirements.some(r => r.id === requirement.id)) {
        allMemberRequirements.push({
          id: participant.requirementId,
          name: requirement?.name || `需求 ${participant.requirementId}`,
          startTime: participant.startTime
        });
      }
    });
    
    // 按开始时间排序，确定固定的位置顺序
    allMemberRequirements.sort((a, b) => new Date(a.startTime) - new Date(b.startTime));
    
    // 获取当天实际工作的需求
    const workingRequirements = [];
    memberParticipants.forEach(participant => {
      // 跳过没有需求ID的记录（无任务人员的空记录）
      if (!participant.requirementId) return;
      
      if (!participant.startTime || !participant.endTime) return;
      
      const start = new Date(participant.startTime);
      const end = new Date(participant.endTime);
      const current = new Date(date);
      
      if (current >= start && current <= end && !this.isWeekend(date)) {
        const requirement = this.requirements[participant.requirementId];
        workingRequirements.push({
          id: participant.requirementId,
          name: requirement?.name || `需求 ${participant.requirementId}`,
          startTime: participant.startTime
        });
      }
    });
    
    // 构建预占位的结果数组，确保位置一致
    const result = [];
    allMemberRequirements.forEach(requirement => {
      const isWorking = workingRequirements.some(r => r.id === requirement.id);
      if (isWorking) {
        result.push(requirement);
      } else {
        // 预占位，保持位置但显示为空
        result.push(null);
      }
    });
    
    return result;
  }

  // 判断是否是需求的第一天
  @action
  isFirstDayOfRequirement(memberId, date, requirementId) {
    const memberParticipants = this.filteredParticipants.filter(p =>
      p.memberId === memberId && p.requirementId === requirementId
    );
    
    for (const participant of memberParticipants) {
      // 跳过没有需求ID或开始时间的记录
      if (!participant.requirementId || !participant.startTime) continue;
      
      const startDate = new Date(participant.startTime);
      const currentDate = new Date(date);
      
      // 如果是需求的第一天
      if (this.formatDateForKey(startDate) === this.formatDateForKey(currentDate)) {
        return true;
      }
    }
    
    return false;
  }

  // 判断是否是需求的最后一天
  @action
  isLastDayOfRequirement(memberId, date, requirementId) {
    const memberParticipants = this.filteredParticipants.filter(p =>
      p.memberId === memberId && p.requirementId === requirementId
    );
    
    for (const participant of memberParticipants) {
      // 跳过没有需求ID或结束时间的记录
      if (!participant.requirementId || !participant.endTime) continue;
      
      const endDate = new Date(participant.endTime);
      const currentDate = new Date(date);
      
      // 如果是需求的最后一天
      if (this.formatDateForKey(endDate) === this.formatDateForKey(currentDate)) {
        return true;
      }
    }
    
    return false;
  }

  // 判断是否应该显示需求名称（只在需求的第一天显示）
  @action
  shouldShowRequirementName(memberId, date, requirementId) {
    return this.isFirstDayOfRequirement(memberId, date, requirementId);
  }

  // 获取需求颜色（确保相邻需求颜色不同）
  @action
  getRequirementColor(requirementId) {
    const colors = [
      'bg-blue-500', 'bg-green-500', 'bg-purple-500', 'bg-orange-500',
      'bg-red-500', 'bg-indigo-500', 'bg-pink-500', 'bg-teal-500'
    ];
    
    // 使用需求ID的哈希值来选择颜色，确保相同需求总是相同颜色
    let hash = 0;
    for (let i = 0; i < requirementId.length; i++) {
      hash = ((hash << 5) - hash) + requirementId.charCodeAt(i);
      hash = hash & hash; // Convert to 32bit integer
    }
    
    const colorIndex = Math.abs(hash) % colors.length;
    return colors[colorIndex];
  }

  // 获取需求名称的显示文本
  @action
  getRequirementAbbr(name) {
    // 根据名称长度智能显示，不扩大列宽
    if (name.length <= 8) {
      return name; // 短名称直接显示
    } else {
      return name.substring(0, 6) + '...'; // 长名称显示前6个字符
    }
  }

  // 检查是否是周末
  @action
  isWeekend(date) {
    const day = new Date(date).getDay();
    return day === 0 || day === 6; // 0 = Sunday, 6 = Saturday
  }

  // 格式化日期显示
  @action
  formatDate(dateString) {
    const date = new Date(dateString);
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const weekDay = date.getDay();
    const weekDays = ['日', '一', '二', '三', '四', '五', '六'];
    
    return `${month}/${day}(${weekDays[weekDay]})`;
  }

  // 格式化日期作为键
  formatDateForKey(date) {
    return date.toISOString().split('T')[0];
  }

  @action
  toggleWeekends(event) {
    this.hideWeekends = event.target.checked;
  }

  @action
  toggleHiddenDates(event) {
    this.hideHiddenDates = event.target.checked;
  }

  @action
  updateQueryStartTime(event) {
    this.queryStartTime = event.target.value;
    this.loadFilteredParticipants();
  }

  @action
  updateQueryEndTime(event) {
    this.queryEndTime = event.target.value;
    this.loadFilteredParticipants();
  }

  @action
  clearFilters() {
    this.initializeTimeRange();
    this.loadFilteredParticipants();
  }
}